import '../../scss/app.scss'
import React from 'react'
import Fragment from '../../components/Fragment'

import {Table, Icon, Row, Col, Form, Input, Button, message} from 'antd'
import RemoteTable from '../../components/RemoteTable'
import { stamp2date } from '../../utils/common'
import ReactDOM from "react-dom";
import {FormReceiver} from "../../utils/FormReceiver";
import { get, post } from '../../utils/http';
import UserForm from './form';
import Validator from "../../validator";
import UserValidator from "../../validator/user";


@Fragment('sys/user')
class App extends React.Component{
    constructor(props) {
        super(props)
        this.state = {
            query:{}
        }
    }

    onEdit = async (record) => {
        const form = { ...record };
        const data = await get('/user/allot', { id: record.id });
        const nodes = data.data.authes;
        let auths = [...data.data.select_authes];
        this.context.modal(
          <UserForm
            record={form}
            nodes={nodes}
            selecteds={[...auths]}
            onAuthChange={ values => auths = values }
          />,
          '编辑用户',
          async () => {
              let validator = new Validator(UserValidator)
              let res = await validator.scene('edit').check(form)
              if(res !== true) {
                  message.error(res)
                  return false
              }
              try{
                  let data = await post('/user/edit', { ...form, auths: auths })
                  message.info(data.msg)
                  this.refs.remoteTable.refresh()
                  return true
              }catch(err){
                  if(Number(err.type) === 1) {
                      message.error(err.error)
                      return false
                  }
              }
          }
        );
    }

    onDelete = async (record) => {
        try{
            let data = await post('/user/del', { id : record.id })
            message.info(data.msg)
            this.refs.remoteTable.refresh();
        }catch(err) {
            if(err.type === 1) {
                message.error(err.error)
            }
        }
    }

    search() {
        this.refs.remoteTable.refresh()
    }
    onAdd = async () => {
        const form = {};
        const data = await get('/user/allot', { id: 0 });
        const nodes = data.data.authes;
        let checkeds = [];
        this.context.modal(
          <UserForm
            record={form}
            nodes={nodes}
            selecteds={[]}
            onAuthChange={(value) => checkeds = value}
          />,
          '新增用户',
          async () => {
              let validator = new Validator(UserValidator)
              let res = await validator.scene('add').check(form)
              if(res !== true) {
                  message.error(res)
                  return false
              }
              try{
                  let data = await post('/user/add', { ...form, auths: checkeds })
                  message.info(data.msg)
                  this.refs.remoteTable.refresh()
                  return true
              }catch(err){
                  if(Number(err.type) === 1) {
                      message.error(err.error)
                      return false
                  }
              }
          }
        );
    }

    render() {
        return (
            <div>
                <Form layout="inline">
                    <Row gutter="8">
                        <Col span="6">
                            <Form.Item label="用户名">
                                <Input type="text" onChange={FormReceiver("username", this.state.query)}/>
                            </Form.Item>
                        </Col>
                        <Col span="6">
                            <Form.Item label="邮箱">
                                <Input type="text" onChange={FormReceiver("email", this.state.query)}/>
                            </Form.Item>
                        </Col>
                        <Col span="6" />
                        <Col span = "6">
                            <div className="app-operation-group">
                                <Button type="primary" onClick={()=>{this.search()}}>查询</Button>
                                <Button type="success" onClick={()=>{this.onAdd()}}>新增</Button>
                            </div>

                        </Col>
                    </Row>

                </Form>
                <RemoteTable
                  ref = 'remoteTable'
                  url = '/user/list'
                  dataProxy={(json) => {
                     let pagination = {
                         pageSize:json.data.records.pageSize,
                         current: json.data.records.cur,
                         total: json.data.records.total,
                     }, data = json.data.records.data;
                     return { pagination, data }
                  }}
                  extend={this.state.query}
                >
                    <Table.Column
                        title = "用户名"
                        dataIndex = "username"
                        key = "username"
                        onFilter={(value, record) => record.username.indexOf(value)}
                    />
                    <Table.Column
                        title = "邮箱"
                        dataIndex = "email"
                        key = "email"
                    />
                    <Table.Column
                        title = "状态"
                        dataIndex="valid"
                        key="valid"
                        render = {val => val == 1?'启用':'禁用'}
                    />
                    <Table.Column
                        title = "注册时间"
                        dataIndex="addtime"
                        key="addtime"
                        render = {val => stamp2date(val)}
                    />
                    <Table.Column
                        title = "操作"
                        key = "action"
                        render = {(text, record) => (
                          <span>
                              <Icon type="edit" onClick={() => {this.onEdit(record)}}/>
                              <Icon type="close" onClick={() => {this.onDelete(record)}}/>
                          </span>
                        )}
                    />
                </RemoteTable>
            </div>

        )
    }
}
ReactDOM.render(
    <App/>,
    document.getElementById('root')
)
